<template>
  <div class="page-user-login">
    <van-nav-bar
      left-arrow
      @click-left="$router.back()"
      title="登录"
    ></van-nav-bar>
    <van-form @submit="onSubmit">
      <van-field
        v-model="form.mobile"
        name="mobile"
        label="手机号"
        placeholder="手机号"
        :rules="[
          { required: true, message: '请填写手机号' },
          { pattern, message: '请输入正确格式的手机号' },
        ]"
      />

      <van-field
        v-model="form.code"
        name="code"
        label="验证码"
        placeholder="验证码"
        :rules="[
          { required: true, message: '请填写验证码' },
          { validator, message: '请输入正确的验证码' },
        ]"
      >
        <!-- 通过具名插槽定制输入框右侧显示的内容 -->
        <template #button>
          <van-button size="small" native-type="button" type="primary"
            >发送验证码</van-button
          >
        </template>
      </van-field>
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { mapActions } from "vuex";
export default {
  data() {
    return {
      // 技巧:变量名和后台接口需要的参数保持一致
      form: {
        mobile: "18563992202",
        code: "246810",
      },
      pattern:
        /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
    };
  },
  created() {
    console.log(this.$route.query.redirectUrl);
  },
  methods: {
    ...mapActions(["getToken"]),
    async onSubmit(values) {
      console.log("submit", values, this.form);
      // this.getToken(values)
      /**
       * 校验通过=>登录
       * 1. 调用vuex的action发送登录请求
       * 2. 成功跳转首页
       */
      // await 使getToken的方法调用同步化
      try {
        await this.getToken(values);
        console.log(1);
        this.$toast.success("登录成功");
        console.log(this.$route.query.redirectUrl);
        this.$router.push("/");
      } catch (error) {
        console.dir(error);
        this.$toast.fail(error.response.data.message);
      }
    },

    // 校验验证码函数 =》校验函数返回 true 表示校验通过，false 表示不通过
    validator(val) {
      console.log("当前校验表单项的值", val);
      if (val.length !== 6) return false;
      return true;
    },
  },
};
</script>

<style scoped lang="less"></style>
